﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ScFramework.Core;
using UnityEngine.UI;
using System;

public class TopFuncLogic : LogicModuleBase<UIManager, SpriteManager>, ICombineSubUI
{
    public void InitGameobject(List<GameObject> obj)
    {
        target = obj.Find(s => s.name == "TopFunc");
        currentEntity = new List<MeshEntityData>();
        allCurrentEntity=new List<MeshEntityData>();
        //    target.transform.Find("BagItemPanel/BagCell").GetComponent<MyButton>().onClick.SetListener(ItemSelect);
        var btn = target.transform.Find("BagItemPanel/BagCell").GetComponent<MyButton>();
        btn.section = 2;
        btn.OnDragTrigged += DispatchAlter;
        btn.OnShowTrigged += DispatchAlter;
        gridBag = target.GetComponentInChildren<GridLayoutGroup>();
        BagType = target.transform.Find("OprationPanel/BagType").gameObject;
        InitBag();
        InitButtons();
        BagItemsList.Add(new Tuple<GameObject, MeshEntityData>(target.transform.Find("BagItemPanel/BagCell").gameObject, null));
        pageText = target.transform.Find("PageTransform/Page").GetComponent<Text>();
        GenBagTable();
        nowBagType = ItemType.All;
    }
    public override void OnEnable()
    {
        base.OnEnable();
        target.gameObject.SetActive(true);
        selected = null;
    }
    public override void OnDisable()
    {
        base.OnDisable();
        target.gameObject.SetActive(false);
    }
    [RegisterEvent(CombineUIEvent.Receive_Data)] 
    void Refresh(List<MeshEntityData> datas)
    {
        //清空后筛出在背包的
        currentEntity.Clear();
        foreach(var t in datas)
        {
            if (t.Body.PresentPos == 2)
            {
                currentEntity.Add(t);
            }
            allCurrentEntity.Add(t);
        }
        List<MeshEntityData> x;
        foreach (var y in bagItems)
        {
            y.Value.Clear();
        }//清空背包
        //分类放入
        for (int i = 0; i < currentEntity.Count; i++)
        {
            if (ItemType.Assist == currentEntity[i].itemType)
            {
                bagItems.TryGetValue(ItemType.Assist, out x);
                x.Add(currentEntity[i]);
            }
            else if (ItemType.Joint == currentEntity[i].itemType)
            {
                bagItems.TryGetValue(ItemType.Joint, out x);
                x.Add(currentEntity[i]);
            }
            else if (ItemType.Weapon == currentEntity[i].itemType)
            {
                bagItems.TryGetValue(ItemType.Weapon, out x);
                x.Add(currentEntity[i]);
            }
        }
        RefreshBag(bagCurrentPage, nowBagType);
    }
    [RegisterEvent( CombineUIEvent.ShowObjectValues)]
    void ChangeSelectedItem(int id)
    {
        if (id <=0)
        {
            selected = null;
        }
        else
        {
            selected = allCurrentEntity.Find(x => x.ID == id);
        }
        RefreshBag(selected);
    }//选中物体改变时传入id，根据id找出对应道具
    [RegisterEvent(CombineUIEvent.BagTypeChanged)]
    void ChangeNowBagType(ItemType x)
    {
        nowBagType = x;
        BagType.transform.Find("Text").GetComponent<Text>().text = nowBagType.ToString();
        RefreshBag(1, nowBagType);
        Dispatch(CombineUIEvent.ShowObjectValues,-1);
    }//背包类型改变时传入背包类型
  /*  [RegisterEvent(CombineUIEvent.BagToBench)]
    void BagToBench()
    {
        RefreshBag(null);
    }*/

    /// <summary>
    /// 刷新背包，对应的页数和当前背包种类
    /// </summary>
    /// <param name="page"></param>
    /// <param name="BagType"></param>
    void RefreshBag(int page, ItemType BagType)
    {
        if (BagType == ItemType.All)
        {
            RefreshBag(page, currentEntity);
        }
        else
        {
            List<MeshEntityData> x;
            bagItems.TryGetValue(BagType, out x);
            RefreshBag(page, x);
        }

    }
    void RefreshBag(int page, List<MeshEntityData> meshEntityDatas)
    {
        //算页数
        bagTotalPage = ((meshEntityDatas.Count + bagCntInRow - 1) / bagCntInRow);
        if (bagTotalPage < 1) bagTotalPage = 1;
        if (page < 1)
        {
            page = 1;
        }
        if (page > bagTotalPage)
        {
            page = bagTotalPage;
        }
        int num = 0;//最后一页的情况
        if (page == bagTotalPage)
        {
            num = meshEntityDatas.Count % bagCntInRow;
            if (num == 0 && meshEntityDatas.Count > 0)
            {
                num = bagCntInRow;
            }
        }
        else
        {
            num = bagCntInRow;
        }

        for (int i = 0; i < bagCntInRow; i++)//绑定对应道具信息
        {
            int x = bagCntInRow * (page - 1) + i;
            if (i < num)
            {
                BagItemsList[i] = new Tuple<GameObject, MeshEntityData>(BagItemsList[i].Item1, meshEntityDatas[x]);
            }
            else
            {
                BagItemsList[i] = new Tuple<GameObject, MeshEntityData>(BagItemsList[i].Item1, null);
            }
            ItemCell.ItemsList = BagItemsList;

        }

        for (int i = 0; i < BagItemsList.Count; i++)//换贴图等
        {
            if (BagItemsList[i].Item2 != null)
            {
                BagItemsList[i].Item1.transform.Find("Image").GetComponent<Image>().sprite = SysModule1.GetSprite(BagItemsList[i].Item2.Body.SpriteName);
                BagItemsList[i].Item1.transform.eulerAngles = new Vector3(0, 0, BagItemsList[i].Item2.Body.MeshRotate * 90);
                BagItemsList[i].Item1.transform.localScale = new Vector3(BagItemsList[i].Item2.Body.IsFliped ? -1 : 1, 1, 1);
            }
            else
            {
                BagItemsList[i].Item1.transform.Find("Image").GetComponent<Image>().sprite = null;
            }

        }
        pageText.text = page + "/" + bagTotalPage;
        bagCurrentPage = page;
        RefreshBag(selected);
    }
    /// <summary>
    /// 根据选中刷新选中物体
    /// </summary>
    /// <param name="selected"></param>
    void RefreshBag(MeshEntityData selected)
    {
        if (selected == null||selected.Body.PresentPos!=2)
        {
            foreach (var x in BagItemsList)
            {
                x.Item1.GetComponent<Image>().color = Color.white;
            }
        }
        else
        {
            foreach (var x in BagItemsList)
            {
                if (x.Item2 == selected)
                {
                    x.Item1.GetComponent<Image>().color = Color.gray;
                }
                else
                {
                    x.Item1.GetComponent<Image>().color = Color.white;
                }
            }
        }
    }
    /// <summary>
    /// 生成背包上的网格
    /// </summary>
    void GenBagTable()
    {
        bagCurrentPage = 1;
        var pannelTrans = BagItemsList[0].Item1.transform.parent;
        bagCntInRow = Mathf.FloorToInt((pannelTrans.GetComponent<RectTransform>().rect.width - gridBag.padding.left) / (gridBag.padding.right + gridBag.cellSize.x)) - 1;
        BagItemsList[0].Item1.name = "bag_1";
        for (int i = 2; i <= bagCntInRow; i++)
        {
            var tp = GameObject.Instantiate(BagItemsList[0].Item1, gridBag.transform);
            tp.GetComponent<MyButton>().OnDragTrigged += DispatchAlter;
            tp.GetComponent<MyButton>().OnShowTrigged += DispatchAlter;
            tp.name = "bag_" + i;
            //tp.GetComponent<MyButton>().onClick.SetListener(ItemSelect);
            BagItemsList.Add(new Tuple<GameObject, MeshEntityData>(tp, null));
        }
        RefreshBag(1, nowBagType);
    }
    /// <summary>
    /// 初始化背包字典
    /// </summary>
    void InitBag()
    {
        bagItems = new Dictionary<ItemType, List<MeshEntityData>>();
        bagItems.Add(ItemType.Joint, new List<MeshEntityData>());
        bagItems.Add(ItemType.Assist, new List<MeshEntityData>());
        bagItems.Add(ItemType.Weapon, new List<MeshEntityData>());
    }
    Button[] buttonList;
    /// <summary>
    /// 初始化按钮组件
    /// </summary>
    void InitButtons()
    {
        buttonList = target.transform.GetComponentsInChildren<Button>(true);
        foreach (Button button in buttonList)
        {
            switch (button.name)
            {
                case "Start":
                    button.onClick.AddListener(OnStartClick);
                    break;
                case "Bag":
                    button.onClick.AddListener(OnBagClick);
                    break;
                case "BagType":
                    button.onClick.AddListener(OnBagTypeClick);
                    break;
                case "Save":
                    button.onClick.AddListener(OnSaveClick);
                    break;
                case "Up":
                    button.onClick.AddListener(UpPage);
                    break;
                case "Down":
                    button.onClick.AddListener(DownPage);
                    break;
            }
        }
    }
    public static int GetId(int x)
    {
        if (x < 0 || x > 8)
        {
            return -1;
        }
        else
        {
            if (BagItemsList[x].Item2 == null)
            {
                return -1;
            }
            else
            {
                return (int)BagItemsList[x].Item2.ID;
            }
        }
        
    }
    void OnStartClick()
    {
        Dispatch(CombineUIEvent.Start);
        Debug.Log("游戏开始了");
    }
    void OnBagClick()
    {
        Debug.Log("背包打开了");
    }
    void OnSaveClick()
    {
        Debug.Log("游戏保存了");
    }
    void OnBagTypeClick()
    {
        int x = (int)nowBagType;
        if (x < 3)
        {
            x++;
        }
        else
        {
            x = 0;
        }
        Dispatch(CombineUIEvent.BagTypeChanged, (ItemType)x);

    }
    void UpPage()
    {
        RefreshBag(bagCurrentPage - 1, nowBagType);
        Dispatch(CombineUIEvent.ShowObjectValues,-1);
    }
    void DownPage()
    {
        RefreshBag(bagCurrentPage + 1, nowBagType);
        Dispatch(CombineUIEvent.ShowObjectValues, -1);
    }


    void DispatchAlter(CombineUIEvent evt, int id)
    {
        Dispatch(evt, id);
    }

    /// <summary>
    /// 当前背包页数
    /// </summary>
    int bagCurrentPage=1;
    /// <summary>
    /// 一排的格子数
    /// </summary>
    int bagCntInRow;
    /// <summary>
    /// 背包总页数
    /// </summary>
    int bagTotalPage;
    /// <summary>
    /// 界面显示背包页数的文本
    /// </summary>
    Text pageText;
    /// <summary>
    /// 当前游戏物体
    /// </summary>
    GameObject target;
    /// <summary>
    /// 背包种类
    /// </summary>
    GameObject BagType;
    /// <summary>
    /// 遮挡物
    /// </summary>
    GameObject Block;
    /// <summary>
    /// 当前持有的在背包中的物体
    /// </summary>
    List<MeshEntityData> currentEntity;
    /// <summary>
    /// 当前持有的所有物体
    /// </summary>
    List<MeshEntityData> allCurrentEntity;
    /// <summary>
    /// 背包分类
    /// </summary>
    Dictionary<ItemType, List<MeshEntityData>> bagItems;
    /// <summary>
    /// 当前选中的物体
    /// </summary>
    MeshEntityData selected;
    /// <summary>
    /// 现在需要显示的背包种类
    /// </summary>
    ItemType nowBagType;
    /// <summary>
    /// 背包格与物体数据绑定
    /// </summary>
    static List<Tuple<GameObject, MeshEntityData>> BagItemsList = new List<Tuple<GameObject, MeshEntityData>>();
    GridLayoutGroup gridBag;
    
}
